﻿/*
 * 由SharpDevelop创建。
 * 用户： zhwang
 * 日期: 2015/6/30
 * 时间: 20:12
 * 
 * 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件
 */
using System;
using System.Windows.Forms;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.EditorInput;
using System.Text.RegularExpressions;


namespace zhwang2008
{
	/// <summary>
	/// Description of SXK_Form.
	/// </summary>
	public partial class SXK_Form : Form
	{

        Autodesk.AutoCAD.Colors.Color entity_color = new Autodesk.AutoCAD.Colors.Color();

        Autodesk.AutoCAD.Colors.Color entity_Ftront_color = new Autodesk.AutoCAD.Colors.Color();

        Autodesk.AutoCAD.Colors.Color entity_Background_color = new Autodesk.AutoCAD.Colors.Color();
		
		[CommandMethod("xgsxk")]
		public void EmployeeCount()
		{
			SXK_Form form_sxk = new SXK_Form();

			Autodesk.AutoCAD.ApplicationServices.Application.ShowModalDialog(form_sxk);

			//			xzsxk();

		}

		public SXK_Form()
		{

			//
			// The InitializeComponent() call is required for Windows Forms designer support.
			//
			InitializeComponent();

			//
			// TODO: Add constructor code after the InitializeComponent() call.
			//
		}

		void TextBox1TextChanged(object sender, EventArgs e)
		{

		}

		void Button1Click(object sender, EventArgs e)
		{

			//			this.Hide();

			xzsxk();

			this.comboBox1.SelectedIndex = 0;
			this.richTextBox1.Text = "";

			this.richTextBox1.AppendText("获取带有属性的块的名称");

			this.richTextBox1.AppendText("\n");

			this.richTextBox1.AppendText("共有" + this.comboBox1.Items.Count.ToString() + "个不同块名的属性快");

			if (comboBox1.Items.Count > 0) {

				button2.Enabled = true;

				Button2Click(null, null);

			}


			//			this.Show();


		}
		//选择属性快，列举属性快名称
		void xzsxk()
		{
			Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

			Editor acEd = doc.Editor;

			string all_strs = "";

			comboBox1.Items.Clear();

			comboBox2.Items.Clear();

			// Build a conditional filter list so that only

			// entities with the specified properties are

			// selected

			TypedValue[] filList = new TypedValue[1];

			filList[0] = new TypedValue((int)DxfCode.Start, "INSERT");

			SelectionFilter sf = new SelectionFilter(filList);

			PromptSelectionResult psr = acEd.SelectAll(sf);


			

			if (psr.Status == PromptStatus.OK) {

				SelectionSet SS = psr.Value;
	
				ObjectId[] idArray = SS.GetObjectIds();

				for (int i = 0; i < idArray.Length; i++) {
					using (Transaction acTrans = doc.Database.TransactionManager.StartTransaction()) {
						// 检查以确定返回的 SelectedObject 对象是有效的     Check to make sure a valid SelectedObject object was returned

						// 以写的方式打开选择的对象   Open the selected object for write

						Entity A_ent = acTrans.GetObject(idArray[i], OpenMode.ForRead) as Entity;

						if (A_ent is BlockReference) {
							BlockReference block_Ref = A_ent as BlockReference;

							//							block_Ref.Highlight();

							if (block_Ref.AttributeCollection.Count > 0) {

								if (all_strs.Contains(block_Ref.Name.ToString()) == false) {

									this.comboBox1.Items.Add(block_Ref.Name.ToString());
								}

								all_strs = all_strs + "-" + block_Ref.Name.ToString();

							}
						}

						acTrans.Commit();
					}

				}

			}

		}
		//获取属性块中的标签

		void Get_tag_val(string block_name, string tag_name, out string tag_val)
		{

			List<string> strs_val = new List<string>();

			string str_val = "";

			Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

			Editor acEd = doc.Editor;


			TypedValue[] filList = new TypedValue[1];

			filList[0] = new TypedValue((int)DxfCode.BlockName, block_name);

			SelectionFilter sf = new SelectionFilter(filList);

			PromptSelectionResult psr = acEd.SelectAll(sf);

			if (psr.Status == PromptStatus.OK) {

				SelectionSet SS = psr.Value;

				ObjectId[] idArray = SS.GetObjectIds();

				for (int i = 0; i < idArray.Count(); i++) {
					using (Transaction acTrans = doc.Database.TransactionManager.StartTransaction()) {
						// 检查以确定返回的 SelectedObject 对象是有效的     Check to make sure a valid SelectedObject object was returned

						// 以写的方式打开选择的对象   Open the selected object for write

						Entity A_ent = acTrans.GetObject(idArray[i], OpenMode.ForWrite) as Entity;

						if (A_ent is BlockReference) {

							BlockReference block_Ref = A_ent as BlockReference;

							//							block_Ref.Highlight();

							foreach (ObjectId att_id in block_Ref.AttributeCollection) {
								AttributeReference attRef = acTrans.GetObject(att_id, OpenMode.ForRead, false) as AttributeReference;

								if (attRef.Tag.Contains(tag_name)) {

									str_val = attRef.TextString;

									if (str_val.Trim().Length > 0) {

										if (!strs_val.Contains(str_val)) {

											strs_val.Add(str_val);

										}

									}

								}

							}

						}

						acTrans.Commit();
					}

				}

			}

			tag_val = "属性有多个值，请慎重修改";


			if (strs_val.Count() > 1) {

				tag_val = "属性有多个值，请慎重修改";

			}
			if (strs_val.Count() == 1) {

				tag_val = "属性的值为<" + strs_val[0] + ">";

			}

			if (strs_val.Count() == 0) {

				tag_val = "属性当前值为空";

			}

		}

		void BQLIST(string block_name)
		{

			Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

			Editor acEd = doc.Editor;

			TypedValue[] filList = new TypedValue[1];

			filList[0] = new TypedValue((int)DxfCode.BlockName, block_name);

			SelectionFilter sf = new SelectionFilter(filList);

			PromptSelectionResult psr = acEd.SelectAll(sf);

			if (psr.Status == PromptStatus.OK) {

				SelectionSet SS = psr.Value;

				ObjectId[] idArray = SS.GetObjectIds();

				for (int i = 0; i < 1; i++) {
					using (Transaction acTrans = doc.Database.TransactionManager.StartTransaction()) {
						// 检查以确定返回的 SelectedObject 对象是有效的     Check to make sure a valid SelectedObject object was returned

						// 以写的方式打开选择的对象   Open the selected object for write

						Entity A_ent = acTrans.GetObject(idArray[i], OpenMode.ForWrite) as Entity;

						if (A_ent is BlockReference) {
							BlockReference block_Ref = A_ent as BlockReference;

							//							block_Ref.Highlight();

							foreach (ObjectId att_id in block_Ref.AttributeCollection) {
								AttributeReference attRef = acTrans.GetObject(att_id, OpenMode.ForWrite, false) as AttributeReference;

								this.comboBox2.Items.Add(attRef.Tag.ToString());

							}

						}

						acTrans.Commit();
					}

				}

			}

		}

		void XG_SXZ(string tag_str, string val_str, string block_name)
		{

			Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

			Editor acEd = doc.Editor;

			TypedValue[] filList = new TypedValue[1];

			filList[0] = new TypedValue((int)DxfCode.BlockName, block_name);

			SelectionFilter sf = new SelectionFilter(filList);

			PromptSelectionResult psr = acEd.SelectAll(sf);

			if (psr.Status == PromptStatus.OK) {

				SelectionSet SS = psr.Value;

				ObjectId[] idArray = SS.GetObjectIds();

				for (int i = 0; i < idArray.Count(); i++) {
					using (Transaction acTrans = doc.Database.TransactionManager.StartTransaction()) {
						// 检查以确定返回的 SelectedObject 对象是有效的     Check to make sure a valid SelectedObject object was returned

						// 以写的方式打开选择的对象   Open the selected object for write

						Entity A_ent = acTrans.GetObject(idArray[i], OpenMode.ForWrite) as Entity;


						if (A_ent is BlockReference) {
							BlockReference block_Ref = A_ent as BlockReference;

							block_Ref.Highlight();

							foreach (ObjectId att_id in block_Ref.AttributeCollection) {
								AttributeReference attRef = acTrans.GetObject(att_id, OpenMode.ForWrite, false) as AttributeReference;

								if (attRef.Tag.ToString() == tag_str) {

									attRef.TextString = val_str;

								}

							}

						}

						acTrans.Commit();
					}

				}

			}

            acEd.Regen();

		}
		/// <summary>
		/// 修改选定标签的位置
		/// </summary>
		/// <param name="tag_str">标签字符串</param>
		/// <param name="val_str">值字符串</param>
		/// <param name="block_name">块名字符串</param>
		/// <param name="JL"></param>
		void XG_SXZ_POS(string tag_str, string val_str, string block_name, double JL)
		{

			Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

			Editor acEd = doc.Editor;

			TypedValue[] filList = new TypedValue[1];

			filList[0] = new TypedValue((int)DxfCode.BlockName, block_name);

			SelectionFilter sf = new SelectionFilter(filList);

			PromptSelectionResult psr = acEd.SelectAll(sf);

			if (psr.Status == PromptStatus.OK) {

			

				SelectionSet SS = psr.Value;

				ObjectId[] idArray = SS.GetObjectIds();

				for (int i = 0; i < idArray.Count(); i++) {
					using (Transaction acTrans = doc.Database.TransactionManager.StartTransaction()) {
						// 检查以确定返回的 SelectedObject 对象是有效的     Check to make sure a valid SelectedObject object was returned

						// 以写的方式打开选择的对象   Open the selected object for write

						Entity A_ent = acTrans.GetObject(idArray[i], OpenMode.ForWrite) as Entity;


						if (A_ent is BlockReference) {
							
							BlockReference block_Ref = A_ent as BlockReference;

							block_Ref.Highlight();

							foreach (ObjectId att_id in block_Ref.AttributeCollection) {
								
//								Tool.AddCircle(block_Ref.GeometricExtents.MinPoint, 10);
								
								AttributeReference attRef = acTrans.GetObject(att_id, OpenMode.ForWrite, false) as AttributeReference;
								
								if (attRef.Tag.ToString() == tag_str) {

//									attRef.TextString = val_str;
									
									acEd.WriteMessage(attRef.AlignmentPoint.X.ToString() + "\n");
									
									acEd.WriteMessage(attRef.AlignmentPoint.Y.ToString() + "\n");
									
									
//									Tool.AddCircle(attRef.AlignmentPoint, 10);
									
									if (Math.Abs(JL) <= 0.0001 && !tag_str.Contains("页")) {
										
										double jl = block_Ref.GeometricExtents.MaxPoint.Y - block_Ref.GeometricExtents.MinPoint.Y;
										
										double jl_Modify = 0;
										
										if (block_Ref.Name.Contains("A3")) {
											
											jl_Modify = jl / 297 * 16;
											
										} else if (block_Ref.Name.Contains("A2")) {
											
											jl_Modify = jl / 420 * 16;
													
										} else {

											jl_Modify = jl / 594 * 16;
											
										}
		
										attRef.AlignmentPoint = new Point3d(attRef.AlignmentPoint.X, block_Ref.GeometricExtents.MinPoint.Y + jl_Modify, attRef.AlignmentPoint.Z);
										
									} else {
										
										attRef.AlignmentPoint = new Point3d(attRef.AlignmentPoint.X, attRef.AlignmentPoint.Y + JL, attRef.AlignmentPoint.Z);
										
									}
									
				
//									attRef.AlignmentPoint = new Point3d(attRef.AlignmentPoint.X, attRef.AlignmentPoint.Y + 10, attRef.AlignmentPoint.Z);
									

									acEd.WriteMessage(attRef.AlignmentPoint.X.ToString() + "\n");
									
									acEd.WriteMessage(attRef.AlignmentPoint.Y.ToString() + "\n");
			
									acEd.WriteMessage("我运行了");

								}

							}
							
							

						}
						
					

						acTrans.Commit();
					}

				}

			}

            acEd.Regen();

		}

		void Add_Pt_At_Block_Pos(string tag_str, string val_str, string block_name)
		{

			Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

			Editor acEd = doc.Editor;

			TypedValue[] filList = new TypedValue[1];

			filList[0] = new TypedValue((int)DxfCode.BlockName, block_name);

			SelectionFilter sf = new SelectionFilter(filList);

			PromptSelectionResult psr = acEd.SelectAll(sf);

			if (psr.Status == PromptStatus.OK) {

		

				SelectionSet SS = psr.Value;

				ObjectId[] idArray = SS.GetObjectIds();

				for (int i = 0; i < idArray.Count(); i++) {
					
					using (Transaction acTrans = doc.Database.TransactionManager.StartTransaction()) {
						// 检查以确定返回的 SelectedObject 对象是有效的     Check to make sure a valid SelectedObject object was returned

						// 以写的方式打开选择的对象   Open the selected object for write

						Entity A_ent = acTrans.GetObject(idArray[i], OpenMode.ForWrite) as Entity;


						if (A_ent is BlockReference) {
							
							BlockReference block_Ref = A_ent as BlockReference;

							block_Ref.Highlight();

							foreach (ObjectId att_id in block_Ref.AttributeCollection) {
								
								AttributeReference attRef = acTrans.GetObject(att_id, OpenMode.ForWrite, false) as AttributeReference;
								
								if (attRef.Tag.ToString() == tag_str) {

									
									double h = 0;
									
									try {
							
										h = Convert.ToDouble(attRef.TextString);
										
//										Tool.Add_Point(new Point3d(block_Ref.Position.X, block_Ref.Position.Y, h));
										
										AddCircle((new Point3d(block_Ref.Position.X, block_Ref.Position.Y, h)), 1.23456);
										
									} catch (System.Exception) {
										
//										
										attRef.ColorIndex = 6;
										
//										throw;
										continue;

//										h = 999999;
										
//										Tool.Add_Point(new Point3d(block_Ref.Position.X, block_Ref.Position.Y, h));
										
//										Tool.AddCircle((new Point3d(block_Ref.Position.X, block_Ref.Position.Y, h)), 1.23456);
										
									}
		
								}

								acEd.WriteMessage("在指定位置添加点，我运行了");

							}

						}
							
						acTrans.Commit();

					}

				}

			}

		}
		
	

		//修改属性标签对应的文字高度、自宽和颜色
		void XG_Text_Op(string block_name, string tag_name, string tag_textOp_name, string tag_textOp_val)
		{
			double zigao = 1;
			double zikuan = 0.7;
			short colour = 0;
			bool do_or_not = true;
	
	

			if (tag_textOp_name.Contains("文字高度")) {

				try {
					zigao = Convert.ToDouble(tag_textOp_val);

					do_or_not = true;

					if (zigao < 0) {

						do_or_not = false;

						this.textBox3.Text = "输入的数值无效";

					}

				} catch (System.Exception) {

					do_or_not = false;

					this.textBox3.Text = "输入的数值无效";

					//					throw;
				}
			}

			if (tag_textOp_name.Contains("文字宽度系数")) {

				try {

					zikuan = Convert.ToDouble(tag_textOp_val);

					do_or_not = true;

					if (zikuan < 0) {

						do_or_not = false;

						this.textBox3.Text = "输入的数值无效";

					}



				} catch (System.Exception) {

					do_or_not = false;

					this.textBox3.Text = "输入的数值无效";

					//					throw;
				}
			}

			if (tag_textOp_name.Contains("文字颜色")) {

				try {


					colour = Convert.ToInt16(tag_textOp_val);

					do_or_not = true;

					if (colour >= 256 || colour < 0) {

						do_or_not = false;

						this.textBox3.Text = "输入的数值无效";

					}

				} catch (System.Exception) {

					do_or_not = false;

					this.textBox3.Text = "输入的数值无效";

					//					throw;
				}
			}
		

			if (do_or_not == true) {

				Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

				Editor acEd = doc.Editor;


				TypedValue[] filList = new TypedValue[1];

				filList[0] = new TypedValue((int)DxfCode.BlockName, block_name);

				SelectionFilter sf = new SelectionFilter(filList);

				PromptSelectionResult psr = acEd.SelectAll(sf);

				if (psr.Status == PromptStatus.OK) {

					SelectionSet SS = psr.Value;

					ObjectId[] idArray = SS.GetObjectIds();
			
					ObjectId oId = new ObjectId();
					
					bool hasTextStyle = false;
			
					if (tag_textOp_name.Contains("文字样式")) {
						
						using (Transaction acTrans = doc.Database.TransactionManager.StartTransaction()) {
							
							TextStyleTable texTbl = acTrans.GetObject(doc.Database.TextStyleTableId, OpenMode.ForRead) as TextStyleTable;
							
							
							if (texTbl.Has(textBox3.Text)) {
								
								hasTextStyle = true;
									
								oId = texTbl[textBox3.Text];
	
								
				
							}
							
							acTrans.Abort();
						}
						
			
					}

					for (int i = 0; i < idArray.Count(); i++) {
						
						using (Transaction acTrans = doc.Database.TransactionManager.StartTransaction()) {
				
							// 检查以确定返回的 SelectedObject 对象是有效的     Check to make sure a valid SelectedObject object was returned

							// 以写的方式打开选择的对象   Open the selected object for write

							Entity A_ent = acTrans.GetObject(idArray[i], OpenMode.ForWrite) as Entity;

							if (A_ent is BlockReference) {

								BlockReference block_Ref = A_ent as BlockReference;

								block_Ref.Highlight();

								foreach (ObjectId att_id in block_Ref.AttributeCollection) {

									AttributeReference attRef = acTrans.GetObject(att_id, OpenMode.ForWrite, false) as AttributeReference;

									if (attRef.Tag.Contains(tag_name)) {

										if (tag_textOp_name.Contains("文字高度")) {

											attRef.Height = zigao;

										}
										if (tag_textOp_name.Contains("文字宽度系数")) {

											attRef.WidthFactor = zikuan;

										}
										if (tag_textOp_name.Contains("文字颜色")) {

											attRef.ColorIndex = colour;
										}
										
										if (tag_textOp_name.Contains("文字样式")) {
																					
											if (hasTextStyle) {
												
												#if CadVersion08
												
												attRef.TextStyle = oId;
												
												#elif CadVersion13

                                                attRef.TextStyleId = oId;
												
											
												#endif
												
							
											}
						
										}
	
									}

								}

							}

							acTrans.Commit();
						}

					}

				}

                acEd.Regen();

			}

            

		}


        //修改属性标签对应的文字高度、自宽和颜色
        void XG_Text_Color(string block_name, string tag_name, string tag_textOp_name, Autodesk.AutoCAD.Colors.Color entity_color)
        {

            bool do_or_not = true;

            if (tag_textOp_name.Contains("文字颜色"))
            {

                do_or_not = true;

            }

            if (do_or_not == true)
            {

                Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

                Editor acEd = doc.Editor;

                TypedValue[] filList = new TypedValue[1];

                filList[0] = new TypedValue((int)DxfCode.BlockName, block_name);

                SelectionFilter sf = new SelectionFilter(filList);

                PromptSelectionResult psr = acEd.SelectAll(sf);

                if (psr.Status == PromptStatus.OK)
                {

                    SelectionSet SS = psr.Value;

                    ObjectId[] idArray = SS.GetObjectIds();

                    for (int i = 0; i < idArray.Count(); i++)
                    {

                        using (Transaction acTrans = doc.Database.TransactionManager.StartTransaction())
                        {

                            // 检查以确定返回的 SelectedObject 对象是有效的     Check to make sure a valid SelectedObject object was returned

                            // 以写的方式打开选择的对象   Open the selected object for write

                            Entity A_ent = acTrans.GetObject(idArray[i], OpenMode.ForWrite) as Entity;

                            if (A_ent is BlockReference)
                            {

                                BlockReference block_Ref = A_ent as BlockReference;

                                block_Ref.Highlight();

                                foreach (ObjectId att_id in block_Ref.AttributeCollection)
                                {
                                    AttributeReference attRef = acTrans.GetObject(att_id, OpenMode.ForWrite, false) as AttributeReference;

                                    if (attRef.Tag.Contains(tag_name))
                                    {

                                        if (tag_textOp_name.Contains("文字颜色"))
                                        {
                                            attRef.Color = entity_color;

                                            //attRef.ColorIndex = colour;
                                        }

                                    }

                                }

                            }

                            acTrans.Commit();
                        }

                    }

                }

                acEd.Regen();

            }



        }



		
		void XG_Text_POs(string block_name, string tag_name, string tag_textOp_name, string tag_textOp_val)
		{
			double zigao = 1;
			double zikuan = 0.7;
			short colour = 0;
			bool do_or_not = false;

			if (tag_textOp_name.Contains("文字高度")) {

				try {
					zigao = Convert.ToDouble(tag_textOp_val);

					do_or_not = true;

					if (zigao < 0) {

						do_or_not = false;

						this.textBox3.Text = "输入的数值无效";

					}

				} catch (System.Exception) {

					do_or_not = false;

					this.textBox3.Text = "输入的数值无效";

					//					throw;
				}
			}

			if (tag_textOp_name.Contains("文字宽度系数")) {

				try {

					zikuan = Convert.ToDouble(tag_textOp_val);

					do_or_not = true;

					if (zikuan < 0) {

						do_or_not = false;

						this.textBox3.Text = "输入的数值无效";

					}



				} catch (System.Exception) {

					do_or_not = false;

					this.textBox3.Text = "输入的数值无效";

					//					throw;
				}
			}

			if (tag_textOp_name.Contains("文字颜色")) {

				try {

					colour = Convert.ToInt16(tag_textOp_val);

					do_or_not = true;

					if (colour >= 256 || colour < 0) {

						do_or_not = false;

						this.textBox3.Text = "输入的数值无效";

					}

				} catch (System.Exception) {

					do_or_not = false;

					this.textBox3.Text = "输入的数值无效";

					//					throw;
				}
			}

			if (do_or_not == true) {

				Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

				Editor acEd = doc.Editor;


				TypedValue[] filList = new TypedValue[1];

				filList[0] = new TypedValue((int)DxfCode.BlockName, block_name);

				SelectionFilter sf = new SelectionFilter(filList);

				PromptSelectionResult psr = acEd.SelectAll(sf);

				if (psr.Status == PromptStatus.OK) {

					SelectionSet SS = psr.Value;

					ObjectId[] idArray = SS.GetObjectIds();

					for (int i = 0; i < idArray.Count(); i++) {
						using (Transaction acTrans = doc.Database.TransactionManager.StartTransaction()) {
							// 检查以确定返回的 SelectedObject 对象是有效的     Check to make sure a valid SelectedObject object was returned

							// 以写的方式打开选择的对象   Open the selected object for write

							Entity A_ent = acTrans.GetObject(idArray[i], OpenMode.ForWrite) as Entity;

							if (A_ent is BlockReference) {

								BlockReference block_Ref = A_ent as BlockReference;

								block_Ref.Highlight();

								foreach (ObjectId att_id in block_Ref.AttributeCollection) {
									AttributeReference attRef = acTrans.GetObject(att_id, OpenMode.ForWrite, false) as AttributeReference;

									if (attRef.Tag.Contains(tag_name)) {
										
										
										attRef.Position = new Point3d(attRef.Position.X, attRef.Position.Y + 10, 0);
										
										

										if (tag_textOp_name.Contains("文字高度")) {

											attRef.Height = zigao;

											//											MessageBox.Show("我运行了");

										}
										if (tag_textOp_name.Contains("文字宽度系数")) {

											attRef.WidthFactor = zikuan;

											//											MessageBox.Show("我运行了");
										}
										if (tag_textOp_name.Contains("文字颜色")) {

											//											MessageBox.Show("我运行了");

											attRef.ColorIndex = colour;
										}

									}

								}

							}

							acTrans.Commit();
						}

					}

				}

			}

		}
		
		
		
		
		

		void Button2Click(object sender, EventArgs e)
		{
			//			MessageBox.Show(this.comboBox1.Text);

			this.comboBox2.Items.Clear();

			BQLIST(this.comboBox1.Text);

			this.comboBox2.SelectedIndex = 0;

			this.richTextBox1.Text = this.richTextBox1.Text + "\n" + "块" + this.comboBox1.Text + "共有" + this.comboBox2.Items.Count + "个属性";

		}

		void Button3Click(object sender, EventArgs e)
		{
			//			MessageBox.Show(this.comboBox2.Text);
			if (this.comboBox4.Text.ToString().Trim().Length > 0) {

				XG_SXZ(this.comboBox2.Text, this.comboBox4.Text, this.comboBox1.Text);

			}
			string tmp_str = "";

			tmp_str = "块" + comboBox1.Text + "中，标签为 " + comboBox2.Text + " 的属性值已修改" + "为" + comboBox4.Text;

			this.richTextBox1.AppendText("\n" + tmp_str);



		}

		void ComboBox1SelectedIndexChanged(object sender, EventArgs e)
		{

			this.comboBox2.Items.Clear();
			this.comboBox2.Text = "";

			Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

			Editor acEd = doc.Editor;

			TypedValue[] filList = new TypedValue[1];

			filList[0] = new TypedValue((int)DxfCode.BlockName, this.comboBox1.Text);

			SelectionFilter sf = new SelectionFilter(filList);

			PromptSelectionResult psr = acEd.SelectAll(sf);

			if (psr.Status == PromptStatus.OK) {

				SelectionSet SS = psr.Value;

				ObjectId[] idArray = SS.GetObjectIds();

				this.richTextBox1.AppendText("\n" + "共有名为" + this.comboBox1.Text + "的带有属性的块" + idArray.Count().ToString() + "个");


			}

			Button2Click(null, null);

		}

		void Button4Click(object sender, EventArgs e)
		{
			Button3Click(null, null);

			this.Close();
		}

		void ComboBox3SelectedIndexChanged(object sender, EventArgs e)
		{
			comboBox5.Visible = false;
			
			textBox3.Visible = true;

            textBox3.Enabled = true;

			
			if (comboBox3.Text.Contains("文字高度")) {
				
				this.button5.Text = "修改文字高度";

				
			}
			if (comboBox3.Text.Contains("文字宽度系数")) {
				
				this.button5.Text = "修改文字宽度系数";
				
			}
			if (comboBox3.Text.Contains("文字颜色")) {
				
				this.button5.Text = "修改文字颜色";

                comboBox5.Visible = false;

                textBox3.Visible = true;


			}
			
			if (comboBox3.Text.Contains("文字样式")) {
				
				this.button5.Text = "修改文字样式";
				
				comboBox5.Items.Clear();
				
				ShowTextStyleNames();
				
				comboBox5.Visible = true;
				
				textBox3.Visible = false;
				
			}
			

		}

		void ComboBox2SelectedIndexChanged(object sender, EventArgs e)
		{
			this.comboBox3.Items.Clear();

			this.comboBox3.Items.Add("文字高度");

			this.comboBox3.Items.Add("文字宽度系数");

			this.comboBox3.Items.Add("文字颜色");
			
			this.comboBox3.Items.Add("文字样式");

			this.comboBox3.SelectedIndex = 0;

			string str_tag_val = "";

			Get_tag_val(this.comboBox1.Text, this.comboBox2.Text, out str_tag_val);

			this.richTextBox1.AppendText("\n" + str_tag_val);

			string txt_cmb = "";

			foreach (var element in comboBox2.Items) {
				txt_cmb = txt_cmb + element.ToString();
			}

			if (txt_cmb.Contains("图纸名称")) {

				//				MessageBox.Show(txt_cmb);

//				button7.Enabled = true;
			}


		}

		void Button5Click(object sender, EventArgs e)
		{

            if (button5.Text.Trim().Contains("修改文字颜色"))
            {

                Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

                Editor ed = acDoc.Editor;

                Database db = acDoc.Database;

                Autodesk.AutoCAD.Windows.ColorDialog cc = new Autodesk.AutoCAD.Windows.ColorDialog();

                DialogResult dResult = cc.ShowDialog();

                if (dResult == DialogResult.OK)
                {

                    entity_color = cc.Color;

                    textBox3.Text = entity_color.ToString();

                    textBox3.Enabled = false;

                    XG_Text_Color(this.comboBox1.Text, this.comboBox2.Text, this.comboBox3.Text, entity_color);


                }
                else
                {
                    XG_Text_Op(this.comboBox1.Text, this.comboBox2.Text, this.comboBox3.Text, this.textBox3.Text);
                }



            }

		}

		void RichTextBox1TextChanged(object sender, EventArgs e)
		{

			this.richTextBox1.SelectionStart = this.richTextBox1.Text.Length;

			this.richTextBox1.ScrollToCaret();

		}

		void Button6Click(object sender, EventArgs e)
		{
            XG_Text_Op(this.comboBox1.Text, this.comboBox2.Text, this.comboBox3.Text, this.textBox3.Text);

			this.Close();
		}

		void SXK_FormLoad(object sender, EventArgs e)
		{
			button7.Enabled = false;
			
			
			button2.Enabled = false;
			
			comboBox5.Visible = false;
			
			button9.Enabled = false;
			
			button15.Enabled = false;
			
		}

		void Button7Click(object sender, EventArgs e)
		{
			comboBox4.Items.Clear();

			string tmp_str = "";

			for (int i = 0; i < comboBox2.Items.Count; i++) {

				tmp_str = comboBox2.Items[i].ToString();


				//***************************************************************************
				if (tmp_str.Contains("第") && tmp_str.Contains("页")) {

//					tmp_str = MySet.Default.Yema.ToString().Trim();

					if (tmp_str.Length > 0) {

						comboBox4.Items.Add(tmp_str);

					}
				}

				//***************************************************************************
				if (tmp_str.Contains("总") && tmp_str.Contains("页")) {

//					tmp_str = MySet.Default.Zonyema.ToString().Trim();

					if (tmp_str.Length > 0) {
						comboBox4.Items.Add(tmp_str);
					}


				}
				//***************************************************************************
				if (tmp_str.Contains("日") && tmp_str.Contains("期")) {

//					tmp_str = MySet.Default.Riqi.ToString().Trim();

					if (tmp_str.Length > 0) {

						comboBox4.Items.Add(tmp_str);

					}
				}
				//***************************************************************************
				if (tmp_str.Contains("专") && tmp_str.Contains("业")) {

//					tmp_str = MySet.Default.Zhuanye.ToString().Trim();

					if (tmp_str.Length > 0) {

						comboBox4.Items.Add(tmp_str);

					}

				}
				//***************************************************************************
				if (tmp_str.Contains("阶") && tmp_str.Contains("段")) {

//					tmp_str = MySet.Default.Jieduan.ToString().Trim();

					if (tmp_str.Length > 0) {

						comboBox4.Items.Add(tmp_str);

					}

				}
				//***************************************************************************
				if (tmp_str.Contains("工") && tmp_str.Contains("号")) {

//					tmp_str = MySet.Default.Gonghao.ToString().Trim();

					if (tmp_str.Length > 0) {

						comboBox4.Items.Add(tmp_str);

					}

				}
				//***************************************************************************
				if (tmp_str.Contains("版") && tmp_str.Contains("本")) {

//					tmp_str = MySet.Default.Banben.ToString().Trim();

					if (tmp_str.Length > 0) {

						comboBox4.Items.Add(tmp_str);

					}

				}
				//***************************************************************************
				if (tmp_str.Contains("图") && tmp_str.Contains("纸") && tmp_str.Contains("编") && tmp_str.Contains("号")) {

//					tmp_str = MySet.Default.Tuzhibianhao.ToString().Trim();

					if (tmp_str.Length > 0) {

						comboBox4.Items.Add(tmp_str);

					}

				}
				//***************************************************************************
				if (tmp_str.Contains("图") && tmp_str.Contains("纸") && tmp_str.Contains("名") && tmp_str.Contains("称") && !tmp_str.Contains("1")) {

//					tmp_str = MySet.Default.Tuzhimingcheng.ToString().Trim();

					if (tmp_str.Length > 0) {

						comboBox4.Items.Add(tmp_str);

					}

				}
				//***************************************************************************
				if (tmp_str.Contains("图") && tmp_str.Contains("纸") && tmp_str.Contains("名") && tmp_str.Contains("称") && tmp_str.Contains("1")) {

//					tmp_str = MySet.Default.Tuzhimingcheng1.ToString().Trim();

					if (tmp_str.Length > 0) {

						comboBox4.Items.Add(tmp_str);

					}

				}
				//***************************************************************************
				if (tmp_str.Contains("项") && tmp_str.Contains("目") && tmp_str.Contains("名") && tmp_str.Contains("称")) {

//					tmp_str = MySet.Default.Xiangmumingcheng.ToString().Trim();

					if (tmp_str.Length > 0) {

						comboBox4.Items.Add(tmp_str);

					}

				}
				//***************************************************************************
				if (tmp_str.Contains("工") && tmp_str.Contains("程") && tmp_str.Contains("名") && tmp_str.Contains("称")) {

//					tmp_str = MySet.Default.Gongchengmingcheng.ToString().Trim();

					if (tmp_str.Length > 0) {

						comboBox4.Items.Add(tmp_str);

					}

				}
				//***************************************************************************

			}
			comboBox4.SelectedIndex = 0;

		}


		//获得属性块的高程数值，获得属性块到曲线起点的距离，成对写入文本文件
		//分三步走 第一步 获得距离  第二步  按距离排序   第三步 排序后得到距离值并写入文本文件






		//获取属性块




		public static List<BlockReference> Get_blocks(string block_name, string tag_name)
		{
			List<BlockReference> blocks = new List<BlockReference>();

			blocks.Clear();

			Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

			Editor acEd = doc.Editor;


			TypedValue[] filList = new TypedValue[1];

			filList[0] = new TypedValue((int)DxfCode.BlockName, block_name);

			SelectionFilter sf = new SelectionFilter(filList);

			PromptSelectionResult psr = acEd.SelectAll(sf);

			if (psr.Status == PromptStatus.OK) {

				SelectionSet SS = psr.Value;

				ObjectId[] idArray = SS.GetObjectIds();

				for (int i = 0; i < idArray.Count(); i++) {
					using (Transaction acTrans = doc.Database.TransactionManager.StartTransaction()) {
						// 检查以确定返回的 SelectedObject 对象是有效的     Check to make sure a valid SelectedObject object was returned

						// 以写的方式打开选择的对象   Open the selected object for write

						Entity A_ent = acTrans.GetObject(idArray[i], OpenMode.ForWrite) as Entity;

						if (A_ent is BlockReference) {

							BlockReference block_Ref = A_ent as BlockReference;

							block_Ref.Highlight();

							foreach (ObjectId att_id in block_Ref.AttributeCollection) {
								AttributeReference attRef = acTrans.GetObject(att_id, OpenMode.ForWrite, false) as AttributeReference;

								if (attRef.Tag.Contains(tag_name)) {
									blocks.Add(block_Ref);


								}

							}

						}

						acTrans.Commit();
					}

				}

			}

			return blocks;



		}


		
		List <string > blockNames = new List<string>();
		
		void Button9Click(object sender, EventArgs e)
		{
			
			Editor acEd = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;

			Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

			Database acDb = acDoc.Database;
			
			
			
			getBlockNamesA();
			
			foreach (string  name in blockNames) {
				
				Modify_entColor_inBlock(name);
				
				
			}
			
			acEd.Regen();
			
			
		}

		static List<string> names()
		{
			
			List <string> nms = new List<string>();
			
			return nms;
			
			
			
			
		}

		void getBlockNames()
		{
			Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

			Editor acEd = doc.Editor;

			//            string all_strs = "";

			//            comboBox1.Items.Clear();
//
			//            comboBox2.Items.Clear();

			// Build a conditional filter list so that only

			// entities with the specified properties are

			// selected

			TypedValue[] filList = new TypedValue[1];

			filList[0] = new TypedValue((int)DxfCode.Start, "INSERT");

			SelectionFilter sf = new SelectionFilter(filList);

			PromptSelectionResult psr = acEd.SelectAll(sf);


			if (psr.Status == PromptStatus.OK) {

				SelectionSet SS = psr.Value;

				ObjectId[] idArray = SS.GetObjectIds();

				for (int i = 0; i < idArray.Length; i++) {
					using (Transaction acTrans = doc.Database.TransactionManager.StartTransaction()) {
						// 检查以确定返回的 SelectedObject 对象是有效的     Check to make sure a valid SelectedObject object was returned

						// 以写的方式打开选择的对象   Open the selected object for write

						Entity A_ent = acTrans.GetObject(idArray[i], OpenMode.ForRead) as Entity;

						if (A_ent is BlockReference) {
							BlockReference block_Ref = A_ent as BlockReference;

							//							block_Ref.Highlight();

							blockNames.Add(block_Ref.Name.ToString());
							
						}

						acTrans.Commit();
					}

				}

			}

		}
		//获取属性块中的标签

		void getBlockNamesA()
		{
			
			Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;

			Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

			Database acDb = acDoc.Database;
			
			
			using (Transaction acTrans = acDb.TransactionManager.StartTransaction()) {
				
				BlockTable table = (BlockTable)acTrans.GetObject(acDb.BlockTableId, OpenMode.ForRead);
				
				try {

					foreach (ObjectId  idItem in table) {
					
						BlockTableRecord btR = acTrans.GetObject(idItem, OpenMode.ForRead) as BlockTableRecord;
					
						string nm = btR.Name;
						
						if (blockNames.Contains(nm) == false && nm.Contains(@"*") == false) {
				
							blockNames.Add(nm);
							
						}
						
					}
			
				} catch (System.Exception exception) {
					
					Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(exception.Message);
					
				}

				acTrans.Abort();
			}
			
			
		}
		//获取属性块中的标签

		void Modify_entColor_inBlock(string blockName)
		{
			
			Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;

			Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

			Database acDb = acDoc.Database;
			
			
			using (Transaction acTrans = acDb.TransactionManager.StartTransaction()) {
				
				BlockTable table = (BlockTable)acTrans.GetObject(acDb.BlockTableId, OpenMode.ForRead);
				
				try {
					BlockTableRecord record = (BlockTableRecord)acTrans.GetObject(table[blockName], 0);
					
					foreach (ObjectId id in record) {
						Entity entity = (Entity)acTrans.GetObject(id, OpenMode.ForWrite);
						
//						entity.ColorIndex = 3;
						
						entity.Color = entity_color;
						
					}
				} catch (System.Exception exception) {
					Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(exception.Message);
				}

				acTrans.Commit();
			}
			
			
		}
		void Button8Click(object sender, EventArgs e)
		{
			double jl = 0;
				
			XG_SXZ_POS(this.comboBox2.Text, this.comboBox4.Text, this.comboBox1.Text, jl);
				
			this.Close();
			
			
			
		}
		void Button10Click(object sender, EventArgs e)
		{
	
			double jl = Convert.ToDouble(textBox1.Text);
			
			XG_SXZ_POS(this.comboBox2.Text, this.comboBox4.Text, this.comboBox1.Text, jl);
				
			this.Close();
			
	
		}
		void Button11Click(object sender, EventArgs e)
		{
			double jl = Convert.ToDouble(textBox1.Text) * (-1);
			
			XG_SXZ_POS(this.comboBox2.Text, this.comboBox4.Text, this.comboBox1.Text, jl);
				
			this.Close();
	
		}
		void Button12Click(object sender, EventArgs e)
		{
			Add_Pt_At_Block_Pos(this.comboBox2.Text, this.comboBox4.Text, this.comboBox1.Text);
			
			this.Close();
		}
		void Label1Click(object sender, EventArgs e)
		{
	
		}
		void ShowTextStyleNames()
		{
			Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
			
			Editor ed = acDoc.Editor;
			
			Database db = acDoc.Database;

			using (Transaction acTrans = db.TransactionManager.StartTransaction()) {
				
				TextStyleTable texTbl = acTrans.GetObject(db.TextStyleTableId, OpenMode.ForRead) as TextStyleTable;
				
				
				foreach (ObjectId  idItem in texTbl) {
					
					TextStyleTableRecord tstR = acTrans.GetObject(idItem, OpenMode.ForRead) as TextStyleTableRecord;
					
					string nm = tstR.Name;
				
					comboBox5.Items.Add(nm);
		
				}
		
				acTrans.Abort();
			}
			
			comboBox5.SelectedIndex = 0;
		}
		void ComboBox5SelectedIndexChanged(object sender, EventArgs e)
		{
			
			textBox3.Text = comboBox5.SelectedItem.ToString();
			
		}
		void Button13Click(object sender, EventArgs e)
		{
	
			Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
			
			Editor ed = acDoc.Editor;
			
			Database db = acDoc.Database;
			
	
			Autodesk.AutoCAD.Windows.ColorDialog cc = new Autodesk.AutoCAD.Windows.ColorDialog();
	
			DialogResult dResult = cc.ShowDialog();
			
			if (dResult == DialogResult.OK) {
				
				entity_color = cc.Color;
				
				button9.Enabled = true;
				
				button13.Text = "对象颜色将被调整为" + entity_color.ToString();

				if (comboBox6.Items.Count > 0) {
					
					button15.Enabled = true;
					
				}
	
			}
	
			
		}
		void Button15Click(object sender, EventArgs e)
		{
			
			Editor acEd = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;

			Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

			Database acDb = acDoc.Database;
			
			string blockName = comboBox6.SelectedItem.ToString();
			
//			MessageBox.Show(blockName);
	
			Modify_entColor_inBlock(blockName);
		
			acEd.Regen();
	
			
		}
		void Button14Click(object sender, EventArgs e)
		{
	
			getBlockNamesA();
			
			comboBox6.Items.Clear();
			
			List<string> items = new List<string>();
	
			foreach (string  element in blockNames) {
				
				if (items.Contains(element) == false) {
					
					items.Add(element);
				}
	
			}
			
			items.Sort();
		
			foreach (string  element in items) {

				comboBox6.Items.Add(element);
	
			}
		
			
			if (comboBox6.Items.Count < 1) {
				
				button15.Enabled = false;
				
				

			} else {
				comboBox6.SelectedIndex = 0;
			}
					
			
			
			
		
		}
		void Button16Click(object sender, EventArgs e)
		{
			Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

			Editor acEd = doc.Editor;

            Entity ent;
            
            PromptEntityOptions peo = new PromptEntityOptions("\n请选择一个块：");
            
            peo.SetRejectMessage("只支持选择一个块");
            
            peo.AddAllowedClass(typeof(BlockReference),true);
      
            PromptEntityResult entRes = acEd.GetEntity(peo);
            
            DocumentLock m_DocumentLock = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.LockDocument();
            
            Database dbs = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Database;
            
            if (entRes != null)
            {
                if (entRes.Status == PromptStatus.OK)
                {
                    ObjectId obj = entRes.ObjectId;
                    
                    using (Transaction trans = dbs.TransactionManager.StartTransaction())
                    {
                        ent = (Entity)trans.GetObject(obj, OpenMode.ForRead);
                        
                        if (ent is BlockReference)
                        {
                           
                        	BlockReference blkRef = (BlockReference)trans.GetObject(obj, OpenMode.ForRead);
                           
                        	BlockTableRecord btr2 = (BlockTableRecord)trans.GetObject(blkRef.BlockTableRecord, OpenMode.ForWrite);
                            
//                        	ed.WriteMessage("实体名称：" + btr2.Name + Environment.NewLine);
                        	
                        	comboBox6.Items.Clear();
                        	
                        	comboBox6.Items.Add(btr2.Name);
                        	
                        	comboBox6.SelectedIndex=0;
              
                        }
                        trans.Commit();
                    }
                }
            }
            
            m_DocumentLock.Dispose();
 		
		}
		void ComboBox6SelectedIndexChanged(object sender, EventArgs e)
		{
	
			if (button13.Text != "选择修改到的颜色") {
			
				if (comboBox6.Items.Count > 0) {
					
					button15.Enabled = true;
					
				}
				
			}

		}
		
		/// <summary>
		/// 根据半径和圆心创建圆，并直接添加圆到图形当前空间
		/// </summary>
		/// <param name="cpt">圆心坐标</param>
		/// <param name="r">半径</param>
		public static void AddCircle(Point3d cpt, Double r)
		{
			
			Circle c = new Circle(cpt, Vector3d.ZAxis, r);
			
			//Database db = HostApplicationServices.WorkingDatabase; //save some space

			Database db = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Database;

			using (Transaction trans = db.TransactionManager.StartTransaction()) {
				//BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead);
				BlockTableRecord btr = (BlockTableRecord)trans.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
				btr.AppendEntity(c);
				trans.AddNewlyCreatedDBObject(c, true);
				trans.Commit();
			}
		}

        private void button4_Click(object sender, EventArgs e)
        {
            XG_SXZ(comboBox2.Text.Trim(), comboBox4.Text.Trim(), comboBox1.Text.Trim());

            this.Close();

        }

        private void button3_Click(object sender, EventArgs e)
        {
             //XG_SXZ(string tag_str, string val_str, string block_name)

            XG_SXZ(comboBox2.Text.Trim(), comboBox4.Text.Trim(), comboBox1.Text.Trim());


        }

        private void button10_Click(object sender, EventArgs e)
        {
            double jl = Convert.ToDouble(textBox1.Text);

            XG_SXZ_POS(this.comboBox2.Text, this.comboBox4.Text, this.comboBox1.Text, jl);

            //this.Close();

        }

        private void button11_Click(object sender, EventArgs e)
        {
            double jl = Convert.ToDouble(textBox1.Text) * (-1);

            XG_SXZ_POS(this.comboBox2.Text, this.comboBox4.Text, this.comboBox1.Text, jl);

            //this.Close();
        }



        private void button5_TextChanged(object sender, EventArgs e)
        {
       

        }

        private void textBox3_TextChanged(object sender, EventArgs e)
        {

        }

        private void button17_Click(object sender, EventArgs e)
        {

            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Editor acEd = doc.Editor;

            TypedValue[] filList = new TypedValue[1];

            filList[0] = new TypedValue((int)DxfCode.Start, "Mtext");

            SelectionFilter sf = new SelectionFilter(filList);

            PromptSelectionResult psr = acEd.GetSelection(sf);

            if (psr.Status == PromptStatus.OK)
            {

                SelectionSet SS = psr.Value;

                ObjectId[] idArray = SS.GetObjectIds();

                for (int i = 0; i < idArray.Length; i++)
                {
                    using (Transaction acTrans = doc.Database.TransactionManager.StartTransaction())
                    {
                        // 检查以确定返回的 SelectedObject 对象是有效的     Check to make sure a valid SelectedObject object was returned

                        // 以写的方式打开选择的对象   Open the selected object for write

                        Entity A_ent = acTrans.GetObject(idArray[i], OpenMode.ForWrite) as Entity;

                        if (A_ent is MText)
                        {
                            MText  mt = A_ent as MText;


                            if (mt.BackgroundFill == true)
                            {
                                mt.BackgroundFillColor = entity_Background_color;
                            }
                            else
                            {
                                mt.BackgroundFill = true;
                                mt.BackgroundFillColor = entity_Background_color;

                            }

                        }

                        acTrans.Commit();
                    }

                }

            }

            acEd.Regen();

            this.Close();

        }





        private void button18_Click(object sender, EventArgs e)
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Editor acEd = doc.Editor;

            TypedValue[] filList = new TypedValue[1];

            filList[0] = new TypedValue((int)DxfCode.Start, "Mtext");

            SelectionFilter sf = new SelectionFilter(filList);

            PromptSelectionResult psr = acEd.GetSelection(sf);

            if (psr.Status == PromptStatus.OK)
            {

                SelectionSet SS = psr.Value;

                ObjectId[] idArray = SS.GetObjectIds();

                for (int i = 0; i < idArray.Length; i++)
                {
                    using (Transaction acTrans = doc.Database.TransactionManager.StartTransaction())
                    {
                        // 检查以确定返回的 SelectedObject 对象是有效的     Check to make sure a valid SelectedObject object was returned

                        // 以写的方式打开选择的对象   Open the selected object for write

                        Entity A_ent = acTrans.GetObject(idArray[i], OpenMode.ForWrite) as Entity;

                        if (A_ent is MText)
                        {
                            MText mt = A_ent as MText;

                            mt.Color = entity_Ftront_color;

                            //string a = MText.ColorChange;//=="\c"

                            //MessageBox.Show(mt.Contents);


                            short c = entity_Ftront_color.ColorIndex;

                            //MessageBox.Show(c.ToString());

                            //MessageBox.Show(entity_Ftront_color.ColorName);

                            if (c>=1&&c<=255)
                            {
                                mt.Contents = Regex.Replace(mt.Contents, @"\\C\d+", MText.ColorChange + c.ToString());
                            }

                        }

                        acTrans.Commit();
                    }

                }

            }

            acEd.Regen();

            //this.Close();
        }

        private void button21_Click(object sender, EventArgs e)
        {

            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Editor acEd = doc.Editor;

            TypedValue[] filList = new TypedValue[1];

            filList[0] = new TypedValue((int)DxfCode.Start, "Mtext");

            SelectionFilter sf = new SelectionFilter(filList);

            PromptSelectionResult psr = acEd.SelectAll(sf);

            if (psr.Status == PromptStatus.OK)
            {

                SelectionSet SS = psr.Value;

                ObjectId[] idArray = SS.GetObjectIds();

                for (int i = 0; i < idArray.Length; i++)
                {
                    using (Transaction acTrans = doc.Database.TransactionManager.StartTransaction())
                    {
                        // 检查以确定返回的 SelectedObject 对象是有效的     Check to make sure a valid SelectedObject object was returned

                        // 以写的方式打开选择的对象   Open the selected object for write

                        Entity A_ent = acTrans.GetObject(idArray[i], OpenMode.ForWrite) as Entity;

                        if (A_ent is MText)
                        {
                            MText mt = A_ent as MText;

                            //改背景颜色
                            if (mt.BackgroundFill == true)
                            {
                                mt.BackgroundFillColor = entity_Background_color;
                            }
                            else
                            {
                                mt.BackgroundFill = true;
                                mt.BackgroundFillColor = entity_Background_color;

                            }

                        }

                        acTrans.Commit();
                    }

                }

            }

            acEd.Regen();

            this.Close();
        }

        private void button22_Click(object sender, EventArgs e)
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Editor acEd = doc.Editor;

            TypedValue[] filList = new TypedValue[1];

            filList[0] = new TypedValue((int)DxfCode.Start, "Mtext");

            SelectionFilter sf = new SelectionFilter(filList);

            PromptSelectionResult psr = acEd.SelectAll(sf);

            if (psr.Status == PromptStatus.OK)
            {

                SelectionSet SS = psr.Value;

                ObjectId[] idArray = SS.GetObjectIds();

                for (int i = 0; i < idArray.Length; i++)
                {
                    using (Transaction acTrans = doc.Database.TransactionManager.StartTransaction())
                    {
                        // 检查以确定返回的 SelectedObject 对象是有效的     Check to make sure a valid SelectedObject object was returned

                        // 以写的方式打开选择的对象   Open the selected object for write

                        Entity A_ent = acTrans.GetObject(idArray[i], OpenMode.ForWrite) as Entity;

                        if (A_ent is MText)
                        {
                            MText mt = A_ent as MText;

                            mt.Color = entity_Ftront_color;

                            //string a = MText.ColorChange;//=="\c"

                            //MessageBox.Show(mt.Contents);


                            short c = entity_Ftront_color.ColorIndex;

                            //MessageBox.Show(c.ToString());

                            //MessageBox.Show(entity_Ftront_color.ColorName);

                            if (c >= 1 && c <= 255)
                            {
                                mt.Contents = Regex.Replace(mt.Contents, @"\\C\d+", MText.ColorChange + c.ToString());
                            }

                        }

                        acTrans.Commit();
                    }

                }

            }

            acEd.Regen();
        }

        private void button23_Click(object sender, EventArgs e)
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Editor acEd = doc.Editor;

            TypedValue[] filList = new TypedValue[1];

            filList[0] = new TypedValue((int)DxfCode.Start, "Mtext");

            SelectionFilter sf = new SelectionFilter(filList);

            PromptSelectionResult psr = acEd.SelectAll(sf);

            if (psr.Status == PromptStatus.OK)
            {

                SelectionSet SS = psr.Value;

                ObjectId[] idArray = SS.GetObjectIds();

                for (int i = 0; i < idArray.Length; i++)
                {
                    using (Transaction acTrans = doc.Database.TransactionManager.StartTransaction())
                    {
                        // 检查以确定返回的 SelectedObject 对象是有效的     Check to make sure a valid SelectedObject object was returned

                        // 以写的方式打开选择的对象   Open the selected object for write

                        Entity A_ent = acTrans.GetObject(idArray[i], OpenMode.ForWrite) as Entity;

                        if (A_ent is MText)
                        {
                            MText mt = A_ent as MText;

                            mt.Color = entity_Ftront_color;

                            //string a = MText.ColorChange;//=="\c"

                            //MessageBox.Show(mt.Contents);


                            short c = entity_Ftront_color.ColorIndex;

                            //MessageBox.Show(c.ToString());

                            //MessageBox.Show(entity_Ftront_color.ColorName);

                            if (c >= 1 && c <= 255)
                            {
                                mt.Contents = Regex.Replace(mt.Contents, @"\\C\d+", MText.ColorChange + c.ToString());
                            }

                            mt.BackgroundFill = true;

                            mt.BackgroundFillColor = entity_Background_color;


                        }

                        acTrans.Commit();
                    }

                }

            }

            acEd.Regen();
        }

        private void button24_Click(object sender, EventArgs e)
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Editor acEd = doc.Editor;

            TypedValue[] filList = new TypedValue[1];

            filList[0] = new TypedValue((int)DxfCode.Start, "Mtext");

            SelectionFilter sf = new SelectionFilter(filList);

            PromptSelectionResult psr = acEd.GetSelection(sf);

            if (psr.Status == PromptStatus.OK)
            {

                SelectionSet SS = psr.Value;

                ObjectId[] idArray = SS.GetObjectIds();

                for (int i = 0; i < idArray.Length; i++)
                {
                    using (Transaction acTrans = doc.Database.TransactionManager.StartTransaction())
                    {
                        // 检查以确定返回的 SelectedObject 对象是有效的     Check to make sure a valid SelectedObject object was returned

                        // 以写的方式打开选择的对象   Open the selected object for write

                        Entity A_ent = acTrans.GetObject(idArray[i], OpenMode.ForWrite) as Entity;

                        if (A_ent is MText)
                        {
                            MText mt = A_ent as MText;

                            Point3dCollection ptCol = mt.GetBoundingPoints();

                            Point3dCollection ptC = new Point3dCollection();

                            if (ptCol.Count>=4)
                            {
                                ptC.Add(ptCol[0]);

                                ptC.Add(ptCol[1]);

                                ptC.Add(ptCol[3]);

                                ptC.Add(ptCol[2]);

                            }

                            Polyline pl = Create_Polyline_List_pt(ptC,0);

                            pl.Closed = true;

                            ObjectId plId = AppendEntity(pl);

                        }

                        acTrans.Commit();
                    }

                }

            }

            acEd.Regen();
        }


        //*******************************************************************************************************
        /// <summary>
        /// 由三维点集合及线宽创建PolyLine实体
        /// </summary>
        /// <param name="pts"></param>
        /// <param name="Xian_kuan"></param>
        /// <returns></returns>
        public static Polyline Create_Polyline_List_pt(Point3dCollection pts, double Xian_kuan)
        {
            Polyline ent = new Polyline();

            for (int i = 0; i < pts.Count; i++)
            {

                ent.AddVertexAt(i, new Point2d(pts[i].X, pts[i].Y), 0, Xian_kuan, Xian_kuan);

            }

            //			ent.Closed = true;
            return ent;

        }

        /// <summary>
        /// 返回Id的对象添加
        /// </summary>
        /// <param name="ent">单个对象</param>
        /// <returns>对象ObjectID</returns>
        public static ObjectId AppendEntity(Entity ent)
        {
            Database db = HostApplicationServices.WorkingDatabase;
            ObjectId entId;
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead);
                BlockTableRecord btr = (BlockTableRecord)trans.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
                entId = btr.AppendEntity(ent);
                trans.AddNewlyCreatedDBObject(ent, true);
                trans.Commit();
            }
            return entId;
        }

        private void button25_Click(object sender, EventArgs e)
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Editor acEd = doc.Editor;

            TypedValue[] filList = new TypedValue[1];

            filList[0] = new TypedValue((int)DxfCode.Start, "Mtext");

            SelectionFilter sf = new SelectionFilter(filList);

            PromptSelectionResult psr = acEd.GetSelection(sf);

            if (psr.Status == PromptStatus.OK)
            {

                SelectionSet SS = psr.Value;

                ObjectId[] idArray = SS.GetObjectIds();

                for (int i = 0; i < idArray.Length; i++)
                {
                    using (Transaction acTrans = doc.Database.TransactionManager.StartTransaction())
                    {
                        // 检查以确定返回的 SelectedObject 对象是有效的     Check to make sure a valid SelectedObject object was returned

                        // 以写的方式打开选择的对象   Open the selected object for write

                        Entity A_ent = acTrans.GetObject(idArray[i], OpenMode.ForWrite) as Entity;

                        if (A_ent is MText)
                        {
                            MText mt = A_ent as MText;



                            //改背景颜色
                            if (mt.BackgroundFill == true)
                            {
                                mt.BackgroundFillColor = entity_Background_color;
                            }
                            else
                            {
                                mt.BackgroundFill = true;
                                mt.BackgroundFillColor = entity_Background_color;

                            }

                            //改文字颜色
                            mt.Color = entity_Ftront_color;

                            short c = entity_Ftront_color.ColorIndex;

                            if (c >= 1 && c <= 255)
                            {
                                mt.Contents = Regex.Replace(mt.Contents, @"\\C\d+", MText.ColorChange + c.ToString());
                            }

                        }

                        acTrans.Commit();
                    }

                }

            }

            acEd.Regen();

            this.Close();
        }

   




		
	}
}